package com.qidian.buy.goods.service.impl;

import com.qidian.buy.common.pojo.BuyResult;
import com.qidian.buy.goods.mapper.ItemDescMapper;
import com.qidian.buy.goods.mapper.ItemImageMapper;
import com.qidian.buy.goods.vo.ItemVO;
import com.qidian.buy.pojo.Item;
import com.qidian.buy.goods.mapper.ItemMapper;
import com.qidian.buy.goods.service.IItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.pojo.ItemDesc;
import com.qidian.buy.pojo.ItemImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2024-07-17 09:35:59
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Autowired
    private ItemImageMapper itemImageMapper;

    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,timeout = 6000)
    @Override
    public BuyResult saveItem(ItemVO vo) {
        // 保存商品信息
        int saveResult = itemMapper.insert(vo); // 保存成功之后itemId就存在了
        if(saveResult == 1) {
            // 保存商品详情信息
            String itemDesc = vo.getItemDesc();
            ItemDesc desc = new ItemDesc();
            desc.setItemId(vo.getItemId());
            desc.setItemDesc(itemDesc);
            itemDescMapper.insert(desc);
            // 保存商品图片信息
            List<String> images = vo.getImages();
            for (String imgUrl : images){
                ItemImage itemImage = new ItemImage();
                itemImage.setImageUrl(imgUrl);
                itemImage.setItemId(vo.getItemId());
                itemImageMapper.insert(itemImage);
            }
            // 保存商品规格信息  给中间表保存数据
            for (Long speId : vo.getItemSpe()){
                itemMapper.insertItemAndSepRelation(vo.getItemId(),speId);
            }
        }
        return BuyResult.isSuccess(saveResult);
    }

    @Override
    public BuyResult queryByPage(int page, int limit, Item item) {
        Map map = new HashMap();
        map.put("total",itemMapper.selectTotal(item));
        map.put("records",itemMapper.selectByPage((page - 1) * limit,limit,item));
        return BuyResult.success(map);
    }
}
